<template>
  <a-card>
    <div>
      <a-space class="operator">
        <a-button @click="add" type="primary">新建</a-button>
      </a-space>
      <a-form layout="horizontal" style="display: none">
        <div>
          <a-row >
            <a-col :md="6" :sm="24" >
              <a-form-item label="选择园区" :labelCol="{span: 5}" :wrapperCol="{span: 18, offset: 1}">
                <a-select v-model="query.farmId" placeholder="请选择园区" ><!--@change="farmChange"-->
                  <a-select-option
                      v-for="(item, index) in farmList"
                      :key="index" :value="item.FarmId">
                    {{item.FarmName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <div style="margin: 3px 0 0 8px;">
                <a-button type="primary" @click="search">查询</a-button>
                <!--                <a-button style="margin-left: 8px" @click="dataInit">重置</a-button>-->
              </div>
            </a-col>
          </a-row>
        </div>
      </a-form>
      <standard-table :loading="loading"
                      :rowKey="(data, index) => index"
                      :columns="columns"
                      :dataSource="visualList"
      >
        <span slot="disType" slot-scope="disType">
          <span v-if="disType.record.disType===0">电脑</span>
          <span v-if="disType.record.disType===1">手机</span>
        </span>
        <span slot="createdTime" slot-scope="createdTime">
          {{timeFormat(createdTime.record.createdTime)}}
        </span>
        <div slot="action" slot-scope="{text, record, index}">
          <a style="margin-right: 8px" @click="editRecard(record, index)">
            <a-icon type="edit"/>基础信息
          </a>
          <a style="margin-right: 8px" @click="editVisual(record, index)">
            <a-icon type="edit"/>编辑组态
          </a>
          <a style="margin-right: 8px" @click="showVisual(record, index)">
            <a-icon type="edit"/>预览
          </a>
          <a-popconfirm title="确定删除?" @confirm="delRecord(record, index)">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a href="#" style="margin-right: 8px; color: #f5222d"><a-icon type="delete" />删除</a>
          </a-popconfirm>
        </div>
      </standard-table>
    </div>
    <a-modal
        :title="modalTitle"
        width="900px"
        :visible="visible"
        @ok="confirm"
        @cancel="editCancel">
      <a-form-model
          ref="farmForm"
          :model="data"
          :rules="rules"
          :label-col="{span: 4}"
          :wrapper-col="{span: 14}">
        <a-form-model-item label="组态名称" prop="name">
          <a-input v-model="data.name" type="text" />
        </a-form-model-item>
        <a-form-model-item label="模版类型"  ><!--prop="FarmName"-->
          <a-radio-group v-model="data.disType" name="radioGroup" :default-value="1" >
            <a-radio :value="0">
              电脑
            </a-radio>
            <a-radio :value="1">
              手机
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="选择园区"  prop="farmId"><!--prop="FarmName"-->
          <a-select v-model="data.farmId" placeholder="请选择园区" @change="farmChange" :disabled="data.visualId ? true : false">
            <a-select-option
                v-for="(item, index) in farmList"
                :key="index" :value="item.FarmId">
              {{item.FarmName}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </a-card>
</template>

<script>
import { mapGetters } from "vuex";
import {list} from '@/services/farm'
import { FormModel } from 'ant-design-vue';
import StandardTable from '@/components/table/StandardTable'
import {list as greenHouseList} from "@/services/greenhouse";
import {list as devList} from "@/services/dev";
import {save,del,searchFarmId, listByFarm} from "@/services/visual";
import moment from "moment";
const columns = [
  {
    title: '组态名称',
    dataIndex: 'name',
    //scopedSlots: { customRender: 'name' }
    key: 'name'
  },
  {
    title: '类型',
    dataIndex: 'disType',
    key: 'disType',
    scopedSlots: { customRender: 'disType' }
  },
  {
    title: '园区名称',
    dataIndex: 'farmName',
    //scopedSlots: { customRender: 'name' }
    key: 'farmName'
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    scopedSlots: { customRender: 'createdTime' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '400px',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'FarmIndex',
  components: {
    StandardTable,
    FormModel
  },
  computed: {
    ...mapGetters('account', ['user_mobile']),
    timeFormat(e) {
      return e => {
        return moment(e).format('YYYY-MM-DD HH:mm:ss')
      }
    }
  },
  data () {
    return {
      loading: false,
      visible: false,
      modalTitle: '',
      columns: columns,
      farmList: [],
      greenHouseList: [],
      devList: [],
      visualList: [],
      dataIndex: null,
      query: {
        farmId: undefined,
        farmName: undefined,
        greenHouseId: undefined,
        greenHouseName: undefined,
        devId: undefined,
        devCode: undefined,
        devName: undefined
      },
      data: {
        visualId: undefined,
        farmId: undefined,
        farmName: undefined,
        greenHouseId: undefined,
        greenHouseName: undefined,
        devId: undefined,
        devName: undefined,
        name: undefined,
        disType:1,
        isMould:false
      },
      rules: {
        name: [
          { required: true, message: '请输入组态名称', trigger: 'blur' },
        ],
        farmId: [
          { required: true, message: '请选择园区', trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    this.getFarmList();
  },
  mounted() {
    this.$on('change', pagination => {
      console.log(pagination);
    })
  },
  methods: {
    async search() {
      if(!this.query.farmId) {
        this.$message.error('园区未选择')
        return
      }
      let visualLists = await searchFarmId(this.query.farmId);
      this.visualList=visualLists.datas;
    },
    async getDevList() {
      let res = await devList(this.query.greenHouseId)
      this.devList = res.Data
    },
    devChange(e) {
      this.query.devCode = e
    },
    houseChange(e) {
      this.query.greenHouseId = e
      this.queryInit()
      this.getDevList()
    },
    async getGreenHouseList() {
      let res = await greenHouseList(this.query.farmId)
      this.greenHouseList = res.Data
    },
    farmChange(e) {
      this.query.farmId = e
      this.queryInit(true)
      this.getGreenHouseList()
    },
    async getFarmList() {
      this.loading = true
      let res = await list()
      this.farmList = res.Data
      const farmList = res.Data.map(item => {
        return item.FarmId
      })
      const visual = await listByFarm({
        farmIdList: farmList
      })
      this.visualList = visual.datas.map(item => {
        const detail = this.farmList.find(v => v.FarmId == item.farmId)
        return {
          id: item.id,
          name: item.name,
          keycode: item.keycode,
          devCode: item.devCode,
          description: item.description,
          devModelId: item.devModelId,
          disType: item.disType,
          farmId: item.farmId,
          farmName: detail.FarmName,
          createdTime: item.createdTime
        }
      })
      this.loading = false
    },
    showVisual(row) {
      console.log(row)
      window.open("visual/show.html?keyCode="+row.keycode);
    },
    editRecard(row, index) {
      console.log(row,index)
      this.dataIndex = index
      this.data = {...row}
      this.modalTitle = '编辑园区'
      this.visible = true
    },
    editVisual(row,index){
      console.log(row,index)
      window.open("visual/index.html?keyCode="+row.keycode);
    },
    delRecord(row, index) {
      if(!row.id) {
        this.$message.error('无效组态');
        return
      }
      console.log(index);
      del(row.id).then(res => {
        if(res.resp_code == 0) {
          this.$message.success("删除成功")
          this.getFarmList()
        } else this.$message.error("删除失败")
      }).catch(err => {
        console.log(err);
        this.$message.error("删除失败")
      })
    },
    add() {
      this.visible = true
      this.modalTitle = '新建组态'
    },
    confirm() {
      this.$refs.farmForm.validate(valid => {
        console.log(valid)
        // eslint-disable-next-line no-empty
        if (valid){
          console.log(this.data)
          this.data.model=0;
          save(this.data).then(res=>{
            console.log(res);
            if (res.resp_code==0){
              this.$message.success("保存成功")
              this.getFarmList()
            }else{
              this.$message.error(res.resp_msg)
            }
          }).catch(err =>{
            console.log(err);
            this.$message.error("编辑失败")
          })
          this.visible = false
        }
      })
    },
    editCancel() {
      this.visible = false
      this.data = this.$options.data().data
      this.$refs.farmForm.resetFields();
    },
    queryInit(type=false) {
      this.query.devName = undefined
      this.query.devId = undefined
      if(type) {
        this.query.greenHouseId = undefined
        this.query.greenHouseName = undefined
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search{
  margin-bottom: 54px;
}
.fold{
  width: calc(100% - 216px);
  display: inline-block
}
.operator{
  margin-bottom: 18px;
}
@media screen and (max-width: 900px) {
  .fold {
    width: 100%;
  }
}
</style>
